package com.example.mybaseapp.ui

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mybaseapp.R
import com.example.mybaseapp.databinding.ItemPackReceiverBinding

/**
 * 监听所有软件的安装、卸载
 */
class PackReceiverActivity : AppCompatActivity() {
    private val datas= mutableListOf<String>()
    private val myAdapter = MySimpleAdapter(this@PackReceiverActivity, datas)
    private var isResgisterFlag = false
    private val packageChangeReceiver = PackageChangeReceiver()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_pack_receiver)
        initRecyclerView()
        register(this)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun initRecyclerView() {
        findViewById<AppCompatButton>(R.id.btn).apply {
            setOnClickListener {
                datas.add("添加一条数据")
                myAdapter.notifyItemInserted(datas.size-1)
            }
        }
        findViewById<RecyclerView>(R.id.recyclerview).apply {
            layoutManager = LinearLayoutManager(this@PackReceiverActivity)
            adapter = myAdapter

        }
    }

    /**
     * 注册软件安装、卸载的广播
     */
    fun register(context:Context){
        val filter = IntentFilter().apply {
            addAction(Intent.ACTION_PACKAGE_ADDED)
            addAction(Intent.ACTION_PACKAGE_REMOVED)
            addDataScheme("package")
        }
        isResgisterFlag = true
        context.registerReceiver(packageChangeReceiver, filter)
    }

    fun unRegister(context: Context){
        if(isResgisterFlag) {
            context.unregisterReceiver(packageChangeReceiver)
            isResgisterFlag = false
        }
    }


    /**
     * 监听软件的安装、卸载
     */
    inner class PackageChangeReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            val packageName = intent.data?.schemeSpecificPart//返回的是包名

            if (Intent.ACTION_PACKAGE_ADDED == action) {
                Log.d("PackageChangeReceiver", "Package installed: $packageName")
                datas.add("安装了 $packageName")
                myAdapter.notifyItemInserted(datas.size-1)
            } else if (Intent.ACTION_PACKAGE_REMOVED == action) {
                Log.d("PackageChangeReceiver", "Package uninstalled: $packageName")
                datas.add("卸载了 $packageName")
                myAdapter.notifyItemInserted(datas.size-1)
            }
        }
    }

    inner class MySimpleAdapter(private val context: Context, private val itemList: MutableList<String>) : RecyclerView.Adapter<MySimpleAdapter.ViewHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val binding: ItemPackReceiverBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_pack_receiver, parent, false)
            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = itemList[position]
            holder.bind(item,position)
        }

        override fun getItemCount(): Int {
            return itemList.size
        }

        inner class ViewHolder(private val binding: ItemPackReceiverBinding) : RecyclerView.ViewHolder(binding.root) {

            fun bind(item: String, position: Int) {
                binding.txContent.setTag(R.id.key1,item)
                binding.txContent.setTag(R.id.key2,position)
                binding.txContent.text = "$item + ${binding.txContent.getTag(R.id.key1)} + ${binding.txContent.getTag(R.id.key2)}"
                binding.executePendingBindings()
            }
        }
    }

    override fun onDestroy() {
        unRegister(this)
        super.onDestroy()
    }
}